// src/layouts/MainLayout.jsx
import { useState, useEffect } from 'react'
import { Layout, Menu, Button, Drawer, Dropdown, Empty } from 'antd'
import {
  MenuUnfoldOutlined,
  MenuFoldOutlined,
  UserOutlined,
  DashboardOutlined,
  SettingOutlined,
  OrderedListOutlined,
  // FileSearchOutlined,
  // FileProtectOutlined,
  // FileAddOutlined,
  ThunderboltFilled,
} from '@ant-design/icons'
import { Link, Outlet, useLocation, useNavigate } from 'react-router-dom'
// 不再需要导入useAuth，直接使用userStore
import { userStore, dictsStore } from '../stores'
import { observer } from 'mobx-react'
import { MenuProps } from 'antd/lib'

const { Header, Sider, Content } = Layout

const MainLayout = observer(() => {
  const [collapsed, setCollapsed] = useState(false)
  const [drawerVisible, setDrawerVisible] = useState(false)
  const [selectedKeys, setSelectedKeys] = useState<string[]>(['dashboard'])
  const [openKeys, setOpenKeys] = useState<string[]>([])
  const location = useLocation()
  const navigate = useNavigate()

  // 初始化字典
  useEffect(() => {
    dictsStore.initDictsStore()
  }, [])

  // 菜单项配置
  const menuItems = [
    {
      key: 'dashboard',
      icon: <DashboardOutlined />,
      label: <Link to="/dashboard">首页</Link>,
    },
   
  ]

  // 直接使用userStore进行权限检查
  const permedMenuItems = menuItems.filter((item) => {
    const { key } = item
    const wholeKey = 'sp-operate:' + key
    return userStore.checkPermission(wholeKey)
  })

  // 自动跳转到第一个有权限的页面
  useEffect(() => {
    // 只在根路径时执行自动跳转
    if (location.pathname === '/') {
      // 确保用户信息已加载
      userStore.initUserInfo().then(() => {
        // 找到第一个有权限的菜单项
        const firstPermittedItem = permedMenuItems[0]
        if (firstPermittedItem) {
          // 导航到该页面
          navigate(`/${firstPermittedItem.key}`)
        }
      })
    }
  }, [location.pathname, navigate, permedMenuItems])

  // 根据当前路径设置选中的菜单项
  useEffect(() => {
    const path = location.pathname

    if (path === '/') {
      setSelectedKeys(['dashboard'])
    } else if (path.includes('/list')) {
      setSelectedKeys(['list'])
      // 如果是子路径，还需要设置子菜单的选中状态
    } else {
      const k = path.split('/')[1]
      setSelectedKeys([k])
    }
  }, [location.pathname])

  const onUserDropdownClick: MenuProps['onClick'] = ({ key }) => {
    if (key === 'logout') {
      userStore.logout()
    }
  }

  return (
    <Layout className="!min-h-screen">
      {/* PC 端侧边栏 - 在移动端隐藏 */}
      <Sider
        theme="light"
        trigger={null}
        collapsible
        collapsed={collapsed}
        className="hidden md:block"
        width={200}
      >
        <div className="h-8 m-4 bg-gray-200 rounded flex items-center justify-center">
          <span className={collapsed ? 'hidden' : 'text-lg font-bold'}>
            控制台
          </span>
          <ThunderboltFilled
            className={collapsed ? 'text-lg font-bold' : '!hidden'}
          />
        </div>
        {/* <div className="collapse-btn-wrapper flex flex-row justify-end">
          <Button
            type="text"
            icon={collapsed ? <MenuUnfoldOutlined /> : <MenuFoldOutlined />}
            onClick={() => setCollapsed(!collapsed)}
            className="hidden md:block"
          ></Button>
        </div> */}
        <Menu
          theme="light"
          mode="inline"
          selectedKeys={selectedKeys}
          openKeys={openKeys}
          onOpenChange={setOpenKeys}
          items={permedMenuItems}
        />
      </Sider>

      <Layout>
        <Header className="px-4 flex justify-between items-center !bg-[#fff]">
          {/* 移动端菜单按钮 */}
          {/* <Button
            type="text"
            icon={<MenuUnfoldOutlined />}
            onClick={() => setDrawerVisible(true)}
            className="md:!hidden block"
          /> */}
          <div className="md:!block hidden"></div>

          <div className="text-lg font-bold md:hidden">控制台</div>

          <div className="flex items-center">
            <Dropdown
              trigger={['click']}
              arrow
              menu={{
                items: [{ key: 'logout', label: <span>退出登录</span> }],
                onClick: onUserDropdownClick,
              }}
            >
              <div className="cursor-pointer">
                <span className="mr-2">
                  {userStore.userInfo?.fullname || '管理员'}
                </span>
                <UserOutlined />
              </div>
            </Dropdown>
          </div>
        </Header>

        <Content className="m-4 p-4 bg-white rounded">
          {permedMenuItems.length > 0 ? (
            <Outlet />
          ) : (
            <div className="flex justify-center items-center h-full">
              <Empty description="暂无任何页面权限，请联系系统管理员确认" />
            </div>
          )}
        </Content>
      </Layout>

      {/* 移动端抽屉菜单 */}
      {/* <Drawer
        title="菜单"
        placement="left"
        onClose={() => setDrawerVisible(false)}
        open={drawerVisible}
        styles={{ body: { padding: 0 } }}
      >
        <Menu
          mode="inline"
          selectedKeys={selectedKeys}
          openKeys={openKeys}
          onOpenChange={setOpenKeys}
          items={menuItems}
          onClick={() => setDrawerVisible(false)}
        />
      </Drawer> */}
    </Layout>
  )
})

export default MainLayout
